/**
 *  JFTSTool - Java Full Text Search tool.
 *  Copyright (C) <2009>  <grupo JFTS>
 *  This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jftstool.fileParserFramework.docHandler;

import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jftstool.fileParserFramework.IDocumentHandler;
import org.jftstool.fileParserFramework.contentHandler.XHTMLResultHandler;
import org.jftstool.fileParserFramework.exceptions.DocumentHandlerException;
import org.jftstool.fileParserFramework.metadata.DocumentMetaData;
import org.xml.sax.ContentHandler;


/**
 * Parser for Microsoft Word documents.
 * @author grupo JFTS
 *
 */
public class DOCHandler implements IDocumentHandler{
	private static final String SUMMARY_INFORMATION = SummaryInformation.DEFAULT_STREAM_NAME;
    private static final String DOCUMENT_SUMMARY_INFORMATION = DocumentSummaryInformation.DEFAULT_STREAM_NAME;
	
	@Override
	public void getDocument(InputStream is, ContentHandler resultHandler, DocumentMetaData metaData) throws DocumentHandlerException {
		POIFSFileSystem fs = null;
		try {
			fs = new POIFSFileSystem(is);
			Iterator<?> entries = fs.getRoot().getEntries();
	        while (entries.hasNext()) {
	            Entry entry = (Entry) entries.next();
	            String name = entry.getName();
	            if (!(entry instanceof DocumentEntry)) {
	            	//do nothing
	            }
	            else if (SUMMARY_INFORMATION.equals(name) || DOCUMENT_SUMMARY_INFORMATION.equals(name)){
	                _getMetaData((DocumentEntry) entry, metaData);	            
	            }
	            else if ("WordDocument".equals(name)) {
	            	WordExtractor extractor = new WordExtractor(fs);
	            	XHTMLResultHandler result = new XHTMLResultHandler(resultHandler, metaData);			
	    			result.startDocument();	            	
	            	for (String paragraph : extractor.getParagraphText()) {
	            		result.element("p", WordExtractor.stripFields(paragraph));
	            	}
	            	result.endDocument();
	            }
	        }
		}
		catch (Exception e) {
			throw new DocumentHandlerException("Error to read DOC document. Can't extract text");
		}
	}
	
	
	private void _getMetaData(DocumentEntry entry, DocumentMetaData metaData) throws DocumentHandlerException{
		try {		
			PropertySet properties = new PropertySet(new DocumentInputStream(entry));
			if (properties.isSummaryInformation()) {
		        _setMetaData(new SummaryInformation(properties), metaData);
		    }
		    if (properties.isDocumentSummaryInformation()) {
		        _setMetaData(new DocumentSummaryInformation(properties), metaData);
		    }			
		}
		catch(Exception e){
			throw new DocumentHandlerException("Can't get metaData from Microsoft DOC document");
		}
	}	

	
	private void _setMetaData(SummaryInformation summary, DocumentMetaData metaData){
		metaData.set(DocumentMetaData.TITLE, summary.getTitle());
		metaData.set(DocumentMetaData.AUTHOR, summary.getAuthor());		
		metaData.set(DocumentMetaData.LAST_AUTHOR, summary.getLastAuthor());
		metaData.set(DocumentMetaData.SUBJECT, summary.getSubject());		
		metaData.set(DocumentMetaData.KEYWORDS, summary.getKeywords());		
		metaData.set(DocumentMetaData.COMMENTS, summary.getComments());		
		metaData.set(DocumentMetaData.TEMPLATE, summary.getTemplate());
		metaData.set(DocumentMetaData.APPLICATION_NAME, summary.getApplicationName());
		metaData.set(DocumentMetaData.REVISION_NUMBER, summary.getRevNumber());
		metaData.set(DocumentMetaData.CREATION_DATE, summary.getCreateDateTime());		
		metaData.set(DocumentMetaData.CHARACTER_COUNT, summary.getCharCount());
		metaData.set(DocumentMetaData.EDIT_TIME, summary.getEditTime());		
		metaData.set(DocumentMetaData.LAST_SAVED, summary.getLastSaveDateTime());
		metaData.set(DocumentMetaData.PAGE_COUNT, summary.getPageCount());
		metaData.set(DocumentMetaData.SECURITY, summary.getSecurity());
		metaData.set(DocumentMetaData.WORD_COUNT, summary.getWordCount());
		metaData.set(DocumentMetaData.LAST_PRINTED, summary.getLastPrinted());
	}

	
	private void _setMetaData(DocumentSummaryInformation summary, DocumentMetaData metaData){
		metaData.set(DocumentMetaData.COMPANY, summary.getCompany());
		metaData.set(DocumentMetaData.MANAGER, summary.getManager());	
	}	
}